#coding:utf-8
import json
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from lovewith.album.views.modules.album import AlbumApi
from lovewith.share.views.modules.attach import AttachApi



#获取用户灵感板信息
@login_required
def get_album(request):
    album_data =[]
    user_album_data = AlbumApi.get_album_by_user(request.user.id)
    for album in user_album_data:
        album_data.append({
            'id': album.id,
            'name': album.name
        })

    return HttpResponse(json.dumps(album_data))


#添加灵感板
@login_required
def add_album(request):
    album_id = None
    album_name = request.POST.get('album')
    if album_name:
        album_id = AlbumApi.add(album_name, request.user)

    return HttpResponse(json.dumps({'error': False, 'id': album_id}))


#更新灵感板名
@login_required
def upate_album(request):
    result = {'error': True}
    album_id = request.POST.get('aid')
    album_name = request.POST.get('name')

    album_data = AlbumApi.check_data(album_id, request.user.id)
    if album_data:
        AlbumApi.update(album_name, album_data)
        result = {'error': False}

    return HttpResponse(json.dumps(result))


#判断某张图片是否在灵感板中
@login_required
def get_user_album_state(request):
    image_id = request.GET.get('mid')
    added_data = AlbumApi.get_added_album(image_id, request.user.id)

    return HttpResponse(json.dumps(added_data))


#添加到灵感板
@login_required
def add_to_album(request):
    result = {'error': True}
    image_id = request.POST.get('mid')
    album_ids = request.POST.getlist('aid')

    image_data = AttachApi.check_data(image_id)
    if image_data:
        #删除旧数据
        AlbumApi.delete_image_from_album(image_data)
        #添加新数据
        AlbumApi().add_to_album(image_data, album_ids, request.user)
        result = {'error': False}

    return HttpResponse(json.dumps(result))


#删除灵感板
@login_required
def delete_album(request):
    result = {'error': True}
    album_id = request.GET.get('aid')
    album_data = AlbumApi.check_data(album_id, request.user.id)

    if album_data:
        AlbumApi.delete(album_data)
        result = {'error': False}

    return HttpResponse(json.dumps(result))








